﻿using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.RoleManager;
using SJ.Platform.EFCore.Model.UserManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys
{
    /// <summary>
    /// 角色操作类
    /// </summary>
    public class Sys_RoleHandle
    {
        private readonly SJDBContext _context;

        public Sys_RoleHandle(SJDBContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> CreateAsync(SysRole entity)
        {
            try
            {
                _context.SysRoles.Add(entity);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>Create", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(SysRole entity)
        {
            try
            {
                _context.Entry(entity).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>Update", ex);
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(SysRole entity)
        {
            try
            {
                _context.SysRoles.Remove(entity);
                return _context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>Delete", ex);
                return false;
            }
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            try
            {
                var entity = _context.SysRoles.Find(id);
                if (entity != null)
                {
                    _context.SysRoles.Remove(entity);
                    await _context.SaveChangesAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>DeleteById", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SysRole> GetEntityByIdAsync(string id)
        {
            try
            {
                return await _context.SysRoles.FindAsync(id);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>GetEntityById", ex);
            }
            return null;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<SysRole> GetAll(int pageNumber, int pageSize, ref int count, Expression<Func<SysRole, bool>> condition = null)
        {
            try
            {
                var query = _context.SysRoles.AsQueryable();

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }
                count = query.Count();
                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                query = query.Skip(skip).Take(pageSize);

                // 执行查询并返回结果
                return query.ToList();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>GetAll  page", ex);
            }
            return null;
        }

        /// <summary>
        /// 分页获取所有角色
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<(List<SysRole> roles, int count)> GetAllAsync(int pageNumber, int pageSize, Expression<Func<SysRole, bool>> condition = null)
        {
            try
            {
                var query = _context.SysRoles.AsQueryable();

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }

                //总条数
                int count = await query.CountAsync();

                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                query = query.Skip(skip).Take(pageSize);

                // 执行查询并返回结果
                var roles = await query.ToListAsync();

                return (roles, count);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>GetAllAsync  page", ex);
            }
            return (null, 0);
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public async Task<List<SysRole>> GetAllAsync(Expression<Func<SysRole, bool>> condition = null)
        {
            try
            {
                IQueryable<SysRole> query = _context.SysRoles;

                // 如果提供了查询条件，则应用它
                if (condition != null)
                {
                    query = query.Where(condition);
                }

                // 执行查询并返回结果
                return await query.ToListAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>GetAll", ex);
            }
            return null;
        }

        /// <summary>
        /// 根据用户ID获取角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<SysRole>> GetAllByUserIdAsync(string userId)
        {
            try
            {
                var query = from role in _context.SysRoles
                            join r in _context.SysRForeigntoroles on role.Id equals r.RoleId
                            where r.ForeignId == userId && r.ForeignType == 1
                            select role;

                // 执行查询并返回结果
                return await query.ToListAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>GetAll", ex);
            }
            return null;
        }
        /// <summary>
        /// 角色配置
        /// </summary>
        /// <param name="entityList"></param>
        /// <returns></returns>
        public async Task<bool> ConfigureUserRolesAsync(List<SysRForeigntorole> entityList)
        {
            try
            {
                int result = 0;
                if (entityList != null && entityList.Count > 0)
                {
                    foreach (SysRForeigntorole entity in entityList)
                    {
                        _context.SysRForeigntoroles.Add(entity);
                    }
                    result = await _context.SaveChangesAsync();
                }

                return result > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>Create", ex);
                return false;
            }
        }
        /// <summary>
        /// 删除用户对应的角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteRelationByUserIdAsync(string userId)
        {
            try
            {
                var relations = await _context.SysRForeigntoroles.Where(r => r.ForeignId == userId).ToListAsync();
                int count = _context.Database.ExecuteSqlRaw($"delete from sys_r_foreigntorole where ForeignId='{userId}';");
                return relations.Count == count;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Sys_RoleHandle=>DeleteRelationByUserIdAsync", ex);
            }
            return false;
        }
    }
}